package com.eboss2.sbs.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.ChooseOptionAdapter;
import com.eboss2.sbs.adapter.ShopRecordListAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.enums.EnumConsts;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.model.ShopRecord;
import com.eboss2.sbs.model.ShopRecordList;
import com.eboss2.sbs.myapplication.MyApplication;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.utils.LogUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.utils.TimeUtil;
import com.mytools.tool.views.MyListView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Date;
import java.util.List;

public class StoreRecordActivity extends BaseActivity implements OnItemClickListener,  View.OnClickListener {


	private static final String TAG = "StoreRecordActivity";
	private int TYPE_TIME_OPTION = 1;
	private int TYPE_PAY_OPTION = 2;

	private final int REQUEST_CODE_QUERYDATE_FROM = 1;
	private final int REQUEST_CODE_QUERYDATE_TO = 2;

	private PullToRefreshScrollView pullToRefreshScrollView;

	private Date panel_dateFrom = new Date();
	private Date panel_dateTo = new Date();
	private Date query_dateFrom = panel_dateFrom;
	private Date query_dateTo = panel_dateTo;

	private MyListView listview;
	private ShopRecordListAdapter adapter;
	private List<ShopRecordList> datas;

	private AlertDialog dialog_panel;

	//日期选择
	private GridView gv_option_time;
	private ArrayList<String> transaction_values = new ArrayList<String>(){
		{
			add(EnumConsts.TransactionType.ALL.getName());
			add(EnumConsts.TransactionType.Consumption.getName());
//			add(EnumConsts.TransactionType.Withdraw.getName());
			add(EnumConsts.TransactionType.Refund.getName());
//			add(EnumConsts.TransactionType.balanceChange.getName());
//			add(EnumConsts.TransactionType.Profit.getName());
		}
	};
	private BitSet transaction_marks = new BitSet(transaction_values.size());
	private ChooseOptionAdapter adapter_time;
	private int transactionType = EnumConsts.TransactionType.ALL.getCode();



	private TextView tv_date_to, tv_date_from;
	private LinearLayout ly_time_zone;

	//支付方式
	private GridView gv_option_paytype;
	private ArrayList<String> paytype_values = new ArrayList<String>(){
		{
			add(EnumConsts.SqbPayChannel.ALL.getName());
//			add(EnumConsts.SqbPayChannel.CARD_MEMO.getName());
//			add(EnumConsts.SqbPayChannel.CASH_MEMO.getName());
			add(EnumConsts.SqbPayChannel.WEIXIN.getName());
//			add(EnumConsts.SqbPayChannel.ALIPAY.getName());
			add(EnumConsts.SqbPayChannel.WALLET.getName());
			add(EnumConsts.SqbPayChannel.CARD.getName());
		}
	};
	private BitSet paytype_marks = new BitSet(paytype_values.size());
	private ChooseOptionAdapter adapter_paytype;
	private int payType = EnumConsts.SqbPayChannel.ALL.getType();

	private int page = 1;
	private int rows = Config.ROWS;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_store_record);
		MyActivityManager.getInstance().addActivity(this);
		initView();
	}

	private void initView(){
		RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
		relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
		showView(R.id.titleback_btn_back, true);
		setTvText(R.id.tv_title, "商城交易记录");
		showView(R.id.next_sure, true);
		setTvText(R.id.next_sure, "筛选");

		String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
		setTvText(R.id.tv_date_choose, from);

		pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pullToRefreshScrollView);
		pullToRefreshScrollView.setOnRefreshListener(new StoreRecordActivity.MyOnRefreshListener());
		pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);

		datas = new ArrayList<ShopRecordList>();
		listview = (MyListView)findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		adapter = new ShopRecordListAdapter(this, datas);

		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		findViewById(R.id.next_sure).setOnClickListener(this);
		findViewById(R.id.ly_previous).setOnClickListener(this);
		findViewById(R.id.ly_next).setOnClickListener(this);

		listview.setAdapter(adapter);
		showNextDayBtn();

		getdata();
	}

	class MyOnRefreshListener implements PullToRefreshBase.OnRefreshListener2<ScrollView> {
		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			pullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
			String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
			refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			refreshData();
		}
		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
			if (datas.size() == 0) {
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						showErrorMsg("没有更多了");
						pullToRefreshScrollView.onRefreshComplete();
					}
				}, 1000);
			} else {
				page++;
				getdata();
			}
		}
	}

	private void refreshData(){
		datas.clear();
		page = 1;
		getdata();
	}

	private void getdata(){
		showProgress("加载中...");
		RequestParams params = new RequestParams();
		if(payType!= EnumConsts.SqbPayChannel.ALL.getType()){params.put("payType", payType);}
		else{params.put("payType", "");}
		if (transactionType != EnumConsts.TransactionType.ALL.getCode()){
			params.put("transactionType", transactionType);
		}else {
			params.put("transactionType", "");
		}
		params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid() + "");
		params.put("startDate", TimeUtil.getStringFromDate(query_dateFrom, "yyyy-MM-dd"));
		params.put("endDate", TimeUtil.getStringFromDate(query_dateTo, "yyyy-MM-dd"));
		params.put("pageNo", page);
		params.put("pageSize", "15");



		HttpUtil.get(Config.SBS_STORE_RECORD_LIST, params, new HttpUtil.RequestListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void success(String response) {
				disShowProgress();
				try {

					JSONObject result = new JSONObject(response);
					if (!result.optBoolean("status")) {
						showErrorMsg(result.getString("message"));
						// 刷新完成
						pullToRefreshScrollView.onRefreshComplete();
						return;
					}

					Gson gson = new Gson();
					// json数据转换成List
					ShopRecord txRecord = gson.fromJson(result.optString("data"), new TypeToken<ShopRecord>() {
					}.getType());

					if (txRecord == null) {
						pullToRefreshScrollView.onRefreshComplete();
						return;
					}

					setTvText(R.id.tv_num, txRecord.getNumber()+"笔");
					setTvText(R.id.tv_total_money, StringUtil.getMoneyString(txRecord.getFactAmount())+"元");
					setTvText(R.id.tv_settle_money, StringUtil.getMoneyString(txRecord.getAmount())+"元");

					if (txRecord.getShopTradeList() != null) {

						if (txRecord.getShopTradeList().size() > 0) {
							datas.addAll(txRecord.getShopTradeList());
							if (datas.size() > 0) {
								linearLayout(R.id.id_no_data).setVisibility(View.GONE);
								listview.setVisibility(View.VISIBLE);
							} else {
								linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
								listview.setVisibility(View.GONE);
							}

						} else {
							if (datas.size() > 0) {

								linearLayout(R.id.id_no_data).setVisibility(View.GONE);
								listview.setVisibility(View.VISIBLE);
								handler.postDelayed(new Runnable() {

									@Override
									public void run() {
										showErrorMsg("没有更多数据");
									}
								}, 1000);
							} else {
								linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
								listview.setVisibility(View.GONE);
							}
						}
					}
					// 刷新完成
					pullToRefreshScrollView.onRefreshComplete();
					adapter.notifyDataSetChanged();


				} catch (Exception e) {
					e.getMessage();
					LogUtils.e(TAG, e.getMessage());
					pullToRefreshScrollView.onRefreshComplete();
				}
			}

			@Override
			public void failed(Throwable error) {
				disShowProgress();
				showE404();
				pullToRefreshScrollView.onRefreshComplete();
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		switch (v.getId()) {
			case R.id.titleback_btn_back:
				finish();
				break;
			case R.id.next_sure:
				showPanel();
				break;
			case R.id.ly_previous:
				query_dateFrom = TimeUtil.getDateFromDate(query_dateFrom, -1);
				query_dateTo = query_dateFrom;
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				transactionType = EnumConsts.TransactionType.ALL.getCode();
				payType = EnumConsts.SqbPayChannel.ALL.getType();
				setTvText(R.id.tv_date_choose, TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日"));
				showNextDayBtn();
				refreshData();
				break;
			case R.id.ly_next:
				query_dateFrom = TimeUtil.getDateFromDate(query_dateFrom, 1);
				query_dateTo = query_dateFrom;
				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				transactionType = EnumConsts.TransactionType.ALL.getCode();
				payType = EnumConsts.SqbPayChannel.ALL.getType();
				setTvText(R.id.tv_date_choose, TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日"));
				showNextDayBtn();
				refreshData();
				break;
			case R.id.tv_date_from:
//				intent.setClass(mContext, ChooseDateActivity.class);
//				String tmp_date_str_from = TimeUtil.getStringFromDate(panel_dateFrom==null?(new Date()):panel_dateFrom, ChooseDateActivity.FORMAT_DATE);
//				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_from);
//				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
//				intent.putExtra("toDate", TimeUtil.getStringFromDate(panel_dateTo, ChooseDateActivity.FORMAT_DATE));
//				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_FROM);
				DatePickDialog dialog = new DatePickDialog(this);
				//设置上下年分限制
				dialog.setYearLimt(5);
				//设置标题
				dialog.setTitle("选择时间");
				//设置类型
				dialog.setType(DateType.TYPE_YMD);
				//设置消息体的显示格式，日期格式
				dialog.setMessageFormat("yyyy-MM-dd");
				//设置选择回调
				dialog.setOnChangeLisener(null);
				//设置点击确定按钮回调
				dialog.setOnSureLisener(new OnSureLisener() {
					@Override
					public void onSure(Date date) {
						panel_dateFrom = date;
						tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
					}
				});
				dialog.show();
				break;
			case R.id.tv_date_to:
//				intent.setClass(mContext, ChooseDateActivity.class);
//				String tmp_date_str_to = TimeUtil.getStringFromDate(panel_dateTo==null?(new Date()):panel_dateTo, ChooseDateActivity.FORMAT_DATE);
//				intent.putExtra(ChooseDateActivity.PARA_SELECTED_DATE, tmp_date_str_to);
//				intent.putExtra("chooseType", ChooseDateActivity.CHOOSE_BEFORE_TODAY);
//				intent.putExtra("fromDate", TimeUtil.getStringFromDate(panel_dateFrom, ChooseDateActivity.FORMAT_DATE));
//				startActivityForResult(intent, REQUEST_CODE_QUERYDATE_TO);
				DatePickDialog dialog2 = new DatePickDialog(this);
				//设置上下年分限制
				dialog2.setYearLimt(5);
				//设置标题
				dialog2.setTitle("选择时间");
				//设置类型
				dialog2.setType(DateType.TYPE_YMD);
				//设置消息体的显示格式，日期格式
				dialog2.setMessageFormat("yyyy-MM-dd");
				//设置选择回调
				dialog2.setOnChangeLisener(null);
				//设置点击确定按钮回调
				dialog2.setOnSureLisener(new OnSureLisener() {
					@Override
					public void onSure(Date date) {
						panel_dateTo = date;//TimeUtil.getDateFromString(b, ChooseDateActivity.FORMAT_DATE);
						tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
					}
				});
				dialog2.show();
				break;
			case R.id.btn_filter_confirm:

				if(dialog_panel!=null){dialog_panel.dismiss();}

				query_dateFrom = panel_dateFrom;
				query_dateTo = panel_dateTo;

				panel_dateFrom = query_dateFrom;
				panel_dateTo = query_dateTo;
				String from = TimeUtil.getStringFromDate(query_dateFrom, "yyyy年MM月dd日");
				String to = TimeUtil.getStringFromDate(query_dateTo, "yyyy年MM月dd日");
				boolean checkshow = from.equals(to);
				showView(R.id.ly_date_chooser, checkshow?true:false);
				showView(R.id.ly_date_show, checkshow?false:true);
				setTvText(R.id.tv_date_choose, from);
				setTvText(R.id.tv_date_show, from+" - "+to);

				showNextDayBtn();
				refreshData();

				break;
			case R.id.btn_cancel:
				if(dialog_panel!=null){dialog_panel.dismiss();}
				break;
			default:break;
		}
	}

	private void showPanel() {
		dialog_panel = new AlertDialog.Builder(mContext).create();
		dialog_panel.show();
		Window window = dialog_panel.getWindow();

		WindowManager.LayoutParams lp =window.getAttributes();
		lp.x=0;
		lp.y=150;

		// 设置布局
		window.setContentView(R.layout.dialog_shop_record_filter);
		// 设置宽高
		window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// 设置弹出的动画效果
		// show at bottom
		window.setGravity(Gravity.TOP);

		ly_time_zone = (LinearLayout) window.findViewById(R.id.ly_time_zone);
		tv_date_from = (TextView) window.findViewById(R.id.tv_date_from);
		tv_date_to = (TextView) window.findViewById(R.id.tv_date_to);
		tv_date_from.setOnClickListener(this);
		tv_date_to.setOnClickListener(this);

		window.findViewById(R.id.btn_filter_confirm).setOnClickListener(this);
		window.findViewById(R.id.btn_cancel).setOnClickListener(this);

		gv_option_time = (GridView) window.findViewById(R.id.gv_option_time);
		adapter_time = new ChooseOptionAdapter(mContext, transaction_values, transaction_marks);
		gv_option_time.setAdapter(adapter_time);
		gv_option_time.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_TIME_OPTION, arg2);
			}
		});

		gv_option_paytype = (GridView) window.findViewById(R.id.gv_option_paytype);
		adapter_paytype = new ChooseOptionAdapter(mContext, paytype_values, paytype_marks);
		gv_option_paytype.setAdapter(adapter_paytype);
		gv_option_paytype.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				adapterNotify(TYPE_PAY_OPTION, arg2);
			}
		});

		reflashPanel();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK)return;
		switch (requestCode) {
			case REQUEST_CODE_QUERYDATE_FROM:
				String a = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateFrom = TimeUtil.getDateFromString(a, ChooseDateActivity.FORMAT_DATE);
				tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
				break;
			case REQUEST_CODE_QUERYDATE_TO:
				String b = data.getStringExtra(ChooseDateActivity.PARA_SELECTED_DATE);
				panel_dateTo = TimeUtil.getDateFromString(b, ChooseDateActivity.FORMAT_DATE);
				tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
				break;
			default: break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void adapterNotify(int adapterType, int index){
		if(adapterType==TYPE_TIME_OPTION){
			transactionType = EnumConsts.TransactionType.getCodeByName(transaction_values.get(index));
			reflashPanel();
		}
		else if(adapterType==TYPE_PAY_OPTION){
			payType = EnumConsts.SqbPayChannel.getTypeByName(paytype_values.get(index));
			reflashPanel();
		}
	}

	private void reflashPanel(){
		int size1 = transaction_values.size();
		for (int i = 0; i < size1; i++) {
			int type_tmp = EnumConsts.TransactionType.getCodeByName(transaction_values.get(i));
			transaction_marks.set(i, type_tmp==transactionType?true:false);
		}
		ly_time_zone.setVisibility(View.VISIBLE);
//		if(transactionType== EnumConsts.TimeZoneType.CUSTOM.getCode()){
			tv_date_from.setText(TimeUtil.getStringFromDate(panel_dateFrom, "yyyy年MM月dd日"));
			tv_date_to.setText(TimeUtil.getStringFromDate(panel_dateTo, "yyyy年MM月dd日"));
//		}

		int size2 = paytype_values.size();
		for (int i = 0; i < size2; i++) {
			int type_tmp = EnumConsts.SqbPayChannel.getTypeByName(paytype_values.get(i));
			paytype_marks.set(i, type_tmp==payType?true:false);
		}

		adapter_time.notifyDataSetChanged();
		adapter_paytype.notifyDataSetChanged();
	}

	private void showNextDayBtn(){
		String a = TimeUtil.getStringFromDate(query_dateFrom, "yyyyMMdd");
		String b = TimeUtil.getStringFromDate(query_dateTo, "yyyyMMdd");
		String c = TimeUtil.getCurrentDateString("yyyyMMdd");
		showView(R.id.ly_next, !(a.equals(b)&&b.equals(c)));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		startActivity(new Intent(mContext, PointTransDetailActivity.class).putExtra("tradeId", datas.get(position).getId()).putExtra("memberId", datas.get(position).getMemberId()));
	}

	
}
